<template>
	<uni-popup ref="settlePopup" border-radius="20rpx 20rpx 0 0" background-color="#fff"
		@maskClick="popupClose">
		<view class="popup-container">
			<view class="card-top">
				<view>
					<u-row>
						<u-col span="9" v-if="defaultAddress.length">
							<view class="address">
								{{defaultAddress[0].detail}}
							</view>
							<view class="info">
								<text class="name">{{defaultAddress[0].name}}</text>
								<text>{{defaultAddress[0].phone}}</text>
							</view>
						</u-col>
						<u-col span="9" v-else></u-col>
						<u-col span="3">
							<button :animation="animationData" :type="defaultAddress.length ? 'primary' : 'warn'" plain size="mini"
								@click="selectAddress">{{defaultAddress.length ? '修改地址' : '选择地址'}}</button>
						</u-col>
					</u-row>
				</view>
			</view>
			<scroll-view scroll-y class="goods-list">
				<view class="goods-item" v-for="(item, index) in goodsData" :key="item.id">
					<view class="goods-info flex-row" slot='title'>
						<view class="image-container">
							<image class="image" :src="item.mainPic ? apiImgPrefix + item.mainPic : ''"></image>
						</view>
						<view class="info-right">
							<text class="name">{{item.name}}</text>
							<view class="goods-specs flex-row">
								<uni-tag :inverted="true" :text="`母：${item.specs_female[0]}两 · ${item.specs_female[1]}只`" type="success"
									class="uni-tag" />
								<uni-tag :inverted="true" :text="`公：${item.specs_male[0]}两 · ${item.specs_male[1]}只`" type="warning"
									class="uni-tag" />
							</view>
							<view class="flex-row flex-between" style="width: 100%;">
								<text class="price">￥{{item.price}}</text>
								<uni-number-box :min="1" v-model="item.quantity" @change="calculateTotalPrice(index)" />
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="card-footer flex-row">
				<button class="button" @click="orderConfirm"
					style="background-color: #ff5a00; height: 70rpx; border-radius: 30rpx; color: #fff; line-height: 70rpx; font-weight: normal; font-size: 28rpx; width: 100%;">共计￥{{totalPrice}}
					&nbsp;&nbsp;&nbsp;提交订单</button>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import {
		API
	} from '@/config/index.js'
	import {
		getAddressList
	} from "@/utils/wx_address"
	import {
		saveOrder
	} from "@/utils/wx_orders"
	export default {
		options: {
			styleIsolation: 'shared', // 解除样式隔离
		},
		data() {
			return {
				apiImgPrefix: API + '/api/',
				goodsData: [],
				defaultAddress: [],
				addressList: [],
				totalPrice: 0,
				animationData: {},
				openid: uni.getStorageSync('openid'),
				settleFromCart: false
			}
		},
		mounted() {
			uni.$on('buyThisConfirm', data => {
				// console.log('buyThisConfirm', this)
				this.$refs['settlePopup'].open('bottom')
				this.goodsData = [data];
				this.goodsData[0].quantity = 1
				this.totalPrice = data.price
				this.getAddressListData()
				this.settleFromCart = false
			})
			uni.$on('cartSettlement', params => {
				// console.log('cartSettlement', params)
				this.$refs['settlePopup'].open('bottom')
				this.goodsData = params.data;
				this.totalPrice = params.totalPrice
				this.getAddressListData()
				this.settleFromCart = true
			})
			uni.$on('selectedAddressId', id => {
				this.defaultAddress = this.addressList.filter(item => item.id === id)
				// console.log(this.defaultAddress)
			})
		},
		onHide() {
			uni.$off('buyThisConfirm')
			uni.$off('selectedAddressId')
			uni.$off('cartSettlement')
		},
		watch: {
			goodsData: {
				handler: function() {
					this.calculateTotalPrice()
				},
				deep: true
			}
		},
		methods: {
			async getAddressListData() {
				try {
					let res = await getAddressList({
						openid: uni.getStorageSync('openid'),
						pageSize: -1,
						currentPage: 1
					});
					// console.log(res)
					this.addressList = res.data.rows;
					this.defaultAddress = res.data.rows.filter(item => item.isdefault === 1)
					// console.log(this.defaultAddress)
				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}
			},
			popupClose() {
				this.$refs['settlePopup'].close()
			},
			calculateTotalPrice(index) {
				this.totalPrice = this.goodsData.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2)
			},
			startShakeAnimation() {
				// 创建新的动画实例
				this.animation = uni.createAnimation({
					duration: 100, // 单个动画周期的持续时间，这里是 100 毫秒
					timingFunction: "ease-in-out", // 时间曲线
					delay: 0 // 开始前的延迟时间
				});

				// 定义动画关键帧
				this.animation.translateX(-5).step(); // 向左移动 5px
				this.animation.translateX(5).step(); // 向右移动 5px
				this.animation.translateX(-5).step(); // 再次向左移动 5px
				this.animation.translateX(0).step(); // 回到原始位置

				// 循环播放动画
				const loopAnimation = this.animation;
				let loopCount = 0;
				const maxLoops = 20; // 控制循环次数，20 次循环大约等于 2 秒

				const intervalId = setInterval(() => {
					loopCount++;
					this.animationData = loopAnimation.export();

					if (loopCount >= maxLoops) {
						clearInterval(intervalId);
					}
				}, 100); // 每 100 毫秒重复一次动画
			},
			async orderConfirm() {
				if (this.defaultAddress.length) {
					// 订单号生成
					// 获取当前时间戳
					const timestamp = Date.now().toString();
					// 生成一个 4 位的随机数
					const randomPart = Math.floor(Math.random() * 9000 + 1000).toString();
					// 截取openid的一部分
					const partOpenid = this.openid.substring(0, 5)
					// 拼接
					const orderCode = `${partOpenid}${timestamp}${randomPart}`;
					let res = await saveOrder({
						openid: this.openid,
						order_code: orderCode,
						address_id: this.defaultAddress[0].id,
						goods_data: this.goodsData,
						totalPrice: this.totalPrice
					})
					if (res.status === 200) {
						this.popupClose();
						uni.showToast({
							icon: "success",
							title: "订单创建成功！",
							duration: 1000,
							success: (res) => {
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/mine/index'
									})
								}, 1200)
							}
						})
					}
				} else {
					this.animationData = {}
					this.startShakeAnimation()
					uni.showToast({
						icon: "error",
						title: "地址不能为空",
						duration: 1000
					})
				}
			},
			selectAddress() {
				uni.navigateTo({
					url: "/pages/mine/address/index?flag=select"
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.flex-row {
		display: flex;
		align-items: center;
	}

	.flex-between {
		justify-content: space-between;
	}

	/deep/ .popup-container {
		box-sizing: border-box !important;

		.card-top {
			border-bottom: 1px solid #e7e7e7;
			padding: 30rpx;

			.address {
				color: #666;
			}

			.info {
				margin-top: 14rpx;

				.name {
					margin-right: 20rpx;
				}
			}
		}


		.goods-list {
			max-height: 60vh;
			overflow-y: scroll;
			padding: 20rpx 30rpx;

			.goods-item {
				padding: 20rpx;
				border-bottom: 1px dashed #e7e7e7;

				.goods-info {
					padding-bottom: 20rpx;

					.image-container {
						width: 25vw;
						// height: 20vw;
						padding-top: 25vw;
						position: relative;
						overflow: hidden;
						margin-right: 30rpx;

						.image {
							position: absolute;
							left: 0;
							top: 0;
							object-fit: cover;
							width: 100%;
							height: 100%;
						}
					}

					.info-right {
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						height: 25vw;
						width: calc(100% - 30vw);

						.name {
							font-size: 28rpx;
						}

						.uni-tag {
							margin-right: 10rpx;
						}

						.price {
							font-size: 30rpx;
							font-weight: bold;
							color: #ff5a00;
						}
					}
				}
			}
		}

		.card-footer {
			padding-top: 30rpx;
			background-color: #fff;
			box-shadow: 0 -5px 5px #e7e7e7;
		}


	}
</style>